/*
 * Copyright (C) 2013 AndXmppSDK Project <hljdrl@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.drl.xmpp.storage.table;

import java.util.LinkedList;
import java.util.List;

import org.drl.xmpp.TSession;
import org.drl.xmpp.storage.AbstractAccountTable;
import org.drl.xmpp.storage.DataBaseManager;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * @author hljdrl@gmail.com
 * 
 */
public final class SessionTable extends AbstractAccountTable {
	private static final class Fields implements AbstractAccountTable.Fields {

		private Fields() {
		}

		public static final String KEY_UID = "_UID";
		public static final String KEY_FROM = "_FROM";
		public static final String KEY_TO = "_TO";
		public static final String KEY_SESSION_JID = "_SESSION_JID";
		public static final String KEY_BODY = "_BODY";
		public static final String KEY_TIME = "_TIME";

	}

	public static final String TABLE_NAME = "_SESSION";
	public static final String KEYS[] = { Fields._ID, Fields.ACCOUNT,
			Fields.KEY_UID, Fields.KEY_FROM, Fields.KEY_TO,
			Fields.KEY_SESSION_JID, Fields.KEY_BODY, Fields.KEY_TIME };

	private final DataBaseManager databaseManager;

	private final static SessionTable instance;

	static {
		instance = new SessionTable(DataBaseManager.getInstance());
	}

	public static SessionTable getInstance() {
		return instance;
	}

	public SessionTable(DataBaseManager databaseManager) {
		this.databaseManager = databaseManager;
	}

	@Override
	public void create(SQLiteDatabase db) {
		String sql = "CREATE TABLE " + TABLE_NAME + " (" + Fields._ID
				+ " INTEGER PRIMARY KEY," + Fields.ACCOUNT + " TEXT,"
				+ Fields.KEY_UID + " TEXT," + Fields.KEY_SESSION_JID + " TEXT,"
				+ Fields.KEY_BODY + " TEXT," + Fields.KEY_TIME + " TEXT,"
				+ Fields.KEY_TO + " TEXT," + Fields.KEY_FROM + " TEXT);";
		DataBaseManager.execSQL(db, sql);
	}

	public long write(TSession item) {
		if (item == null)
			return -1;
		ContentValues values = new ContentValues();
		values.put(Fields.ACCOUNT, item.getUserName());
		values.put(Fields.KEY_SESSION_JID, item.getSessionJid());
		values.put(Fields.KEY_BODY, item.getBody());
		//
		SQLiteDatabase db = databaseManager.getWritableDatabase();
		if (item.id == null) {
			Cursor c = db.query(getTableName(), getProjection(),
					Fields.KEY_SESSION_JID + " = ?",
					new String[] { item.getSessionJid() }, null, null,
					getListOrder());
			if (hasData(c)) {
				item.id =  (long) db.update(TABLE_NAME, values, Fields.KEY_SESSION_JID + " = ?",
						new String[] { item.getSessionJid() });
			} else {
				return db.insert(TABLE_NAME, Fields.ACCOUNT, values);
			}
			closeCurosr(c);
		} else {
			item.id =  (long) db.update(TABLE_NAME, values, Fields._ID + " = ?",
					new String[] { String.valueOf(item.id) });
		}

		return item.id;
	}

	public void removeSessionItem(TSession item) {
		if (item == null)
			return;
		SQLiteDatabase db = databaseManager.getWritableDatabase();
		if (item.id != null)
			db.delete(TABLE_NAME, Fields._ID+" = ?",
					new String[] { String.valueOf(item.id) });
	}

	public List<TSession> readAllItems() {
		List<TSession> mLm = new LinkedList<TSession>();
		Cursor c = list();
		if (hasData(c)) {
			int idIx = c.getColumnIndex(Fields._ID);
			int atIx = c.getColumnIndex(Fields.ACCOUNT);
			int uidIx = c.getColumnIndex(Fields.KEY_UID);
			int snIx = c.getColumnIndex(Fields.KEY_SESSION_JID);
			int byIx = c.getColumnIndex(Fields.KEY_BODY);
			int teIx = c.getColumnIndex(Fields.KEY_TIME);
			int toIx = c.getColumnIndex(Fields.KEY_TO);
			int fmIx = c.getColumnIndex(Fields.KEY_FROM);
			for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
				String user = c.getString(atIx);
				String contact = c.getString(snIx);
				String body = c.getString(byIx);
				String time = c.getString(teIx);

				TSession mIm = new TSession(user, contact);
				mIm.id = c.getLong(idIx);
				mIm.setBody(body);
				mIm.setTime(time);
				mLm.add(mIm);
			}
		}
		closeCurosr(c);
		return mLm;
	}

	@Override
	protected String getTableName() {
		return TABLE_NAME;
	}

	@Override
	protected String[] getProjection() {
		return KEYS;
	}

}
